package com.example.kafkademo.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.HashMap;
import java.util.Map;

/**
 * 创建生产者对象
 */
public class ProducerTest {
    public static void main(String[] args) {
        //配置集合
        Map<String, Object> map = new HashMap<>();
        map.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.102:9092");
        map.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        map.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //创建生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(map);
        //创建数据
        for (int i = 0; i < 10; i++) {
            ProducerRecord<String, String> record =
                    new ProducerRecord<String, String>("test", "key"+i, "hello"+i);
            //使用生产者对象发送消息到kafka
            kafkaProducer.send(record);
        }

        ProducerRecord<String, String> record =
                new ProducerRecord<String, String>("test", "key", "hello");
        //使用生产者对象发送消息到kafka
        kafkaProducer.send(record);
        //关闭生产者对象
        kafkaProducer.close();
    }
}
